package com.jiyun.service.impl;

import com.github.wxpay.sdk.WXPayUtil;
import com.jiyun.demo.HttpClient;
import com.jiyun.mapper.RechargeMapper;
import com.jiyun.mapper.UserMapper;
import com.jiyun.service.RechargeService;
import com.reading.pojo.OrderVo;
import com.reading.pojo.Recharge;
import com.reading.pojo.RechargeDto;
import com.reading.pojo.RechargeVo;
import com.reading.pojo.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RechargeServiceImpl implements RechargeService {

    @Autowired
    private RechargeMapper rechargeMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveRecharge(Recharge recharge) {
        recharge.setMaketime(new Date());
        rechargeMapper.saveRecharge(recharge);
    }

    @Override
    public String getQrCodeUrl(String code) throws Exception {
        // 创建HttpClient对象，设置请求URL为微信支付统一下单接口
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        httpClient.setHttps(true);

        // 封装微信支付统一下单接口所需的必填参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", "wxab8acb865bb1637e"); // 公众账号ID
        map.put("mch_id", "11473623"); // 商户号
        map.put("nonce_str", WXPayUtil.generateNonceStr()); // 随机字符串
        map.put("body", "会员VIP充值"); // 商品描述
        map.put("out_trade_no", code); // 订单号
        map.put("total_fee", "1"); // 总金额，单位为分
        map.put("spbill_create_ip", "127.0.0.1"); // 终端IP
        map.put("notify_url", "127.0.0.1"); // 通知地址
        map.put("trade_type", "NATIVE"); // 交易类型

        // 生成签名并转换为XML格式参数
        String xmlParam = WXPayUtil.generateSignedXml(map, "2ab9071b06b9f739b950ddb41db2690d");
        httpClient.setXmlParam(xmlParam);

        // 发送POST请求
        httpClient.post();

        // 获取响应内容并解析为Map
        String result = httpClient.getContent();
        Map<String, String> resultMap = WXPayUtil.xmlToMap(result);

        // 提取二维码链接地址
        String codeUrl = resultMap.get("code_url");
        System.out.println("获取到的二维码链接地址为：" + codeUrl);

        return codeUrl;

    }

    @Override
    public String orderquery(Recharge recharge) throws Exception {
        // 调用findResult方法查询订单状态
        String result = findResult(recharge);
        return result;
    }


    /**
     * 循环查询订单状态
     * 该方法在一分钟内每5秒请求一次微信支付订单查询接口，直到订单状态为SUCCESS或超时
     *
     * @param
     * @return 返回订单的交易状态
     * @throws Exception 当网络请求失败或解析响应出错时抛出异常
     */
    public String findResult(Recharge recharge) throws Exception {
        String result = "";
        int i = 0;
        System.out.println(recharge.getCode());
        System.out.println("调用了订单查询接口");

        // 在一分钟内每5秒请求一次订单查询接口
        while (true) {

            String orderStatus = findTrade(recharge.getCode(),recharge.getId());

            if (orderStatus == null) {
                result = "fail";
                System.out.println("支付出错，停止请求");
                break;
            }

            if ("SUCCESS".equals(orderStatus)) {
                result = "success";
                System.out.println("支付成功，停止请求");
                break;
            } else {
                i++;
                System.out.println("支付中，第" + i + "次请求");
                Thread.sleep(5000);
            }

            if (i == 12) {
                result = "fail";
                System.out.println("支付超时，停止请求");
                break;
            }
        }
        return result;
    }

    /**
     * 查询订单状态
     * 该方法通过调用微信支付订单查询接口，获取订单的当前状态
     *
     * @param trade 订单号
     * @return 返回订单的交易状态
     * @throws Exception 当网络请求失败或解析响应出错时抛出异常
     */
    public String findTrade(String trade,Integer id) throws Exception {
        // 创建HttpClient对象，设置请求URL为微信支付订单查询接口
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
        httpClient.setHttps(true);

        // 封装微信支付订单查询接口所需的必填参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", "wxab8acb865bb1637e"); // 公众账号ID
        map.put("mch_id", "11473623"); // 商户号
        map.put("nonce_str", WXPayUtil.generateNonceStr()); // 随机字符串
        map.put("out_trade_no", trade); // 订单号

        // 生成签名并转换为XML格式参数
        String xmlParam = WXPayUtil.generateSignedXml(map, "2ab9071b06b9f739b950ddb41db2690d");
        httpClient.setXmlParam(xmlParam);

        // 发送POST请求
        httpClient.post();

        // 获取响应内容并解析为Map
        String result = httpClient.getContent();
        System.out.println(result);
        Map<String, String> resultMap = WXPayUtil.xmlToMap(result);

        // 提取交易订单状态
        String trade_state = resultMap.get("trade_state");
        System.out.println("获取到的交易订单状态为：" + trade_state);
        if (trade_state.equals("SUCCESS")) {
            //新建rechargeVo类
            RechargeVo rechargeVo = new RechargeVo();
            rechargeVo.setCode(trade);
            rechargeVo.setPaytime(new Date());
            //修改对应的账单信息
            rechargeMapper.updateOne(rechargeVo);
            //获取修改用户的金币，所需的数据
            Recharge one = rechargeMapper.findOne(trade);
            System.out.println("------------------"+one);
            User user = userMapper.findOneUser(one.getUid());
            System.out.println("-----------------user="+user);
            OrderVo orderVo = new OrderVo();
            int glod = user.getUserglod1()+one.getAmount();
            orderVo.setGlod(glod);
            orderVo.setId(user.getId());
            //修改对应的用户金币
            userMapper.updateUserGlod1(orderVo);

            System.out.println("----------"+user);
        }
        return trade_state;
    }

    @Override
    public Recharge findOne(String code) {
        return rechargeMapper.findOne(code);
    }

    @Override
    public void updateOne(RechargeVo rechargeVo) {
        rechargeMapper.updateOne(rechargeVo);
    }

    @Override
    public Recharge findById(Integer id) {
        return rechargeMapper.findById(id);
    }

    @Override
    public List<Recharge> findAll(RechargeDto rechargeDto) {
        return rechargeMapper.findAll(rechargeDto);
    }

    @Override
    public void saveExchange(Recharge recharge) {
        rechargeMapper.saveExchange(recharge);
    }

    @Override
    public String findAllExpenses(Integer id) {
        //查询当前登录用户的所有消费记录
        RechargeDto rechargeDto = new RechargeDto();
        rechargeDto.setId(id);
        rechargeDto.setTypename("2");
        List<Recharge> allExpenses = rechargeMapper.findAll(rechargeDto);
        RechargeDto rechargeDto2 = new RechargeDto();
        rechargeDto2.setId(id);
        rechargeDto2.setTypename("1");
        List<Recharge> allExpenses2= rechargeMapper.findAll(rechargeDto2);
        int i = allExpenses.size();
        int sum = allExpenses.stream().mapToInt(Recharge::getAmount).sum();
        int sum1 = allExpenses2.stream().mapToInt(Recharge::getAmount).sum();
        return sum+","+i+","+sum1;
    }
}
